package com.example.tb;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.mingle.widget.LoadingView;

import org.w3c.dom.Text;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * Created by 汪贵春 on 2016/5/24.
 */
public class SrcActivity extends AppCompatActivity{

    private String data = null;
    private TextView text;
    private LoadingView vLoading;
    private static final int TIME_LIMIT  = 3000;    //设置超时时间
    private Handler handler = new Handler(){

        public void handleMessage(Message msg){
            vLoading.setVisibility(View.INVISIBLE);
            switch (msg.what){
                case 0:
                    text.setText("sorry，连接失败，请查看网络是否通畅。。。");
                    break;
                case 1:
                    text.setText(msg.obj.toString());
                    break;

            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data = getIntent().getStringExtra("word");

        if(data.equals("")){
            this.setTitle("首页");
        }else{
            this.setTitle(data);
        }

        setContentView(R.layout.activity_src);
        text = (TextView) findViewById(R.id.text);
        vLoading = (LoadingView) findViewById(R.id.loading);

        sendHttpURLConnection();

    }

    private void sendHttpURLConnection() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try{
                    URL url = new URL("http://www.iciba.com/" + data);

                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(TIME_LIMIT);
                    connection.setReadTimeout(TIME_LIMIT);
                    connection.connect();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                    String string = "";
                    for(String str = reader.readLine() ; str != null ; str = reader.readLine()){
                        string +=  str + "\n";
                    }

                    Message message = new Message();
                    message.what = 1;
                    message.obj = string;
                    handler.sendMessage(message);

                }catch (SocketTimeoutException | UnknownHostException e ) {
                    //连接主机超时
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
        };
        new Thread(runnable).start();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_src, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.save:
                String fileName;
                if(data.equals("")){
                    fileName = "首页.html";
                }else{
                    fileName = data + ".html";
                }

                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE)));
                    writer.write(text.getText().toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if(writer != null)
                            writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Toast.makeText(this,"保存成功\ndata/data/com.example.tb/files/" + fileName,Toast.LENGTH_LONG).show();
                break;
        }
        return true;
    }
}
